//
//  ForgetPayPWCheckCardInfoController.m
//  HuLaQuan
//
//  Created by hok on 1/23/16.
//  Copyright © 2016 Jianghao. All rights reserved.
//

#import "ForgetPayPWCheckCardInfoController.h"

#import "YuTypeInfoCell.h"
#import "ConfirmButtonCell.h"

//labels
#import "YuUserCellLabel.h"

#import "ForgetPayPWFirstInputPasswordController.h"

//Back To
#import "UserSecurityViewController.h"

//
#import "VerifyRealNameEngine.h"

@interface ForgetPayPWCheckCardInfoController ()<UITextFieldDelegate>

@property (nonatomic,strong) NSArray *items;

/**
 *  卡号
 */
@property(nonatomic,strong)NSString *cardNumber;

/**
 *  身份证号
 */
@property(nonatomic,strong)NSString *userID;

/**
 *  真实姓名
 */
@property(nonatomic,strong)NSString *userRealName;

@property (nonatomic, strong) VerifyRealNameEngine *verifyRealNameEngine;
@end

static NSString * const YuTypeInfoCellIdentifier = @"YuTypeInfoCell";
static NSString * const ConfirmButtonCellIdentifier = @"ConfirmButtonCell";

@implementation ForgetPayPWCheckCardInfoController

- (VerifyRealNameEngine *)verifyRealNameEngine
{
    if (!_verifyRealNameEngine) {
        _verifyRealNameEngine = [[VerifyRealNameEngine alloc] init];
    }
    return _verifyRealNameEngine;
}
- (NSArray *)items
{
    if (!_items) {
        
        NSArray * array  = [NSArray arrayWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"ForgetPayPWInfoItem" ofType:@"plist"]];
        if (self.userCardInfoAndSMSToken && self.userCardInfoAndSMSToken[@"card"]) {
            _items = [array subarrayWithRange:NSMakeRange(0, 2)];
        }else{
            _items = array;
        }
        
    }
    return _items;
}

- (void)setupUI
{
    [self setupNavBackButton];
    
    [self setupFooterForTableView];
    
    [self.tableView registerNib:[YuTypeInfoCell nib] forCellReuseIdentifier:YuTypeInfoCellIdentifier];
    [self.tableView registerNib:[ConfirmButtonCell nib] forCellReuseIdentifier:ConfirmButtonCellIdentifier];
    
    self.title = @"验证银行卡";
    
    [self setupTapGesture];
}
#pragma mark UITableViewDataSource

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    return indexPath.section ==1 ? kConfirmButtonCellHeight : kNormalCellHeight;
    
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return section == 1 ?  1 : self.items.count;
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    
    return   section == 0 ? 40 : 0.000001;
    
    
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section

{
    if (section == 0) {
        CGRect frameRect = CGRectMake(25, 0, 200, 40);
        UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 200, 40)];
        YuUserCellLabel *textSection = [[YuUserCellLabel alloc] initWithFrame:frameRect];
        textSection.text = @"请验证持卡人信息";
        [view addSubview:textSection];
        return view;
    }else{
        return nil;
    }
    
    
    
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (indexPath.section == 0 ) {
        YuTypeInfoCell *cell = [tableView dequeueReusableCellWithIdentifier:YuTypeInfoCellIdentifier
                                                               forIndexPath:indexPath];
        //cell.textField.placeholder = kNumberFiledPlaceholder;
        
        
        cell.textField.delegate = self;
        cell.textField.tag = indexPath.row;
        cell.titleLabel.text = self.items[indexPath.row][@"title"];
        cell.textField.placeholder = self.items[indexPath.row][@"placeholder"];
        
        if (self.userCardInfoAndSMSToken[@"card"] && indexPath.row == 0) {
            cell.textField.text = self.userCardInfoAndSMSToken[@"card"][@"cardId"];
            cell.textField.enabled = NO;
        }
        
        [cell.textField addTarget:self action:@selector(detaileAddressFieldWithText:) forControlEvents:UIControlEventEditingChanged];
        return cell;
        
    }else{
        
        ConfirmButtonCell *cell = [tableView dequeueReusableCellWithIdentifier:ConfirmButtonCellIdentifier
                                                                  forIndexPath:indexPath];
        
        [cell.confirmButton setTitle:@"下一步" forState:UIControlStateNormal];
        
        cell.banksButton.hidden = NO;
        
        [cell.banksButton addTarget:self action:@selector(tapBanksButton) forControlEvents:UIControlEventTouchUpInside];
        cell.confirm = (ClickBlock)^(){
            [self tapNextButton];
        };
        
        
//        if (self.cardNumber.length && self.userID.length)  {
//            cell.confirmButton.enabled = YES;
//        }else{
//            cell.confirmButton.enabled = NO;
//        }
        
        return cell;
    }
    
    
    
    
}

//getInformation
- (void)detaileAddressFieldWithText:(UITextField *)textField
{
    switch (textField.tag) {
        case 0:
            self.cardNumber = textField.text;
            break;
        case 1:
            self.userID = textField.text;
            break;
        default:
            self.userRealName = textField.text;
            break;
    }
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return YES;
}

#pragma mark - Button Events
- (void)tapBanksButton
{
    UIStoryboard *storyBoard = [UIStoryboard storyboardWithName:@"BankCard" bundle:nil];
    [self.navigationController pushViewController:[storyBoard instantiateViewControllerWithIdentifier:@"ValidBankListViewController"] animated:YES];
   // [self presentViewController: animated:YES completion:nil];
}
- (void)tapNextButton
{
    if (self.userCardInfoAndSMSToken[@"card"] ) {
        if (self.userID.length) {
            [YuNetworkStatusUtilities showProgressMessage:NETWORK_LOADING];
            
            [self.verifyRealNameEngine verifyRealName:self.userCardInfoAndSMSToken[@"realName"] ? self.userCardInfoAndSMSToken[@"realName"] : @"" cardInfo:self.userCardInfoAndSMSToken[@"card"] identity:self.userID];
        }else{
            [self.view makeToast:@"银行卡信息未填写完"];
        }
    }else{
        if (self.userID.length && self.userRealName.length &&  self.cardNumber.length) {
            [YuNetworkStatusUtilities showProgressMessage:NETWORK_LOADING];
            
            [self.verifyRealNameEngine verifyRealName:self.userRealName cardInfo:@{@"cardId":self.cardNumber} identity:self.userID];
        }else{
            [self.view makeToast:@"银行卡信息未填写完"];
        }
    }
    
    
    
}



#pragma mark - Call Back

- (void)verifyRealNameFinish:(NSNotification*) notification
{
    [YuNetworkStatusUtilities dismissHUD];
    NSDictionary *messageDic = [notification object];//获取到传递的对象
    if ([messageDic[@"isSuccess"] boolValue]) {
    
        [self performSegueWithIdentifier:@"ShowForgetPayPWFirstInputPasswordFromInfo" sender:self];
        
    }else{
        [self showNetWorkError:messageDic[@"message"]];
        
    }
    
}

#pragma mark - Life Cycle
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:YES];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(verifyRealNameFinish:) name:@"VerifyRealNameFinish" object:nil];
    
    NSLog(@"very real name controller  %@",self.userCardInfoAndSMSToken);
    
}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:YES];
    
    
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"VerifyRealNameFinish" object:nil];
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
#pragma mark - Navigation Back
//- (void)goBackAction
//{
//    [[UIApplication sharedApplication].keyWindow endEditing:YES];
//    UIAlertController *x = [UIAlertController alertWithTitle:@"提示" andMessage:@"是否放弃忘记支付密码操作" andBlock:^(UIAlertAction *action ) {
//        if ([action.title isEqualToString:@"好的"]) {
//            if ([self.navigationController.viewControllers[1] isKindOfClass:[UserSecurityViewController class]]) {
//                [self.navigationController popToViewController:self.navigationController.viewControllers[1] animated:YES];
//            }
//        }
//        
//    }  type:@"confirmAndCancel"];
//    [self presentViewController:x animated:YES completion:nil];
//    
//}

#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
    
    if ([[segue identifier] isEqualToString:@"ShowForgetPayPWFirstInputPasswordFromInfo"]) {
        ForgetPayPWFirstInputPasswordController *controller = (ForgetPayPWFirstInputPasswordController*) [segue destinationViewController];
        //controller.typeOfCheck = BindingCard;
        controller.type = PayPassword;
        controller.titleOfNav = kSetPayPasswordTitle;
        controller.titleOfPassword = kSetPayPasswordHint;
        return;
    }
}


@end
